package org.small.shop.phone.api.utils;

import javax.annotation.PostConstruct;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

@Component
public class AppConstantUtils {

	private static Logger logger = LoggerFactory.getLogger(AppConstantUtils.class);

	@Resource
	private RedisOperator redisOperators;

	private static RedisOperator redisOperator;

	@PostConstruct
	public void init() {
		redisOperator = redisOperators;
	}

	public static final String APPUSER_SESSION_TO_REDIS_KEY = "appUserSession:";

	public static final String AUTHORIZATION = "authorization";

	public static final String SPLIT_STR = "_";

	public static final String SPLIT_STR1 = "-";
	
	public static final Integer AGREE_COUNT = 3;
	
	public static final String AGREE_COUNT_FLAG = "agree_count_flag";

	public static synchronized String getAppId(HttpServletRequest request) {

		String token = getTokenStr(request.getHeader(AppConstantUtils.AUTHORIZATION));
		if (!StringUtils.isEmpty(token)) {
			try {
				return redisOperator.get(AppConstantUtils.APPUSER_SESSION_TO_REDIS_KEY + token);
			} catch (Exception e) {
				logger.info(e.getMessage());
			}
		}
		return null;
	}

	private static String getTokenStr(String authorization) {

		if (!StringUtils.isEmpty(authorization)) {

			int indexOf = authorization.indexOf("{");
			int lastIndexOf = authorization.lastIndexOf("}");
			if (indexOf > 0 && lastIndexOf > 0) {
				String subStr = authorization.substring(indexOf + 1, lastIndexOf);
				return !StringUtils.isEmpty(subStr) ? subStr : null;
			}
		}
		return null;
	}

}
